<?php
	/*
		Convert each text into a well-formed XHTML
		@param string $folder_name the path to the book directory
		@param string $input_file the path to the input XHTML file
	*/
	function convertText($folder_name,$input_file) {
		echo "tidying text <br />";
		//tidy the html
		tidyText($folder_name, $input_file);
		
		echo "fix the path to image <br />";
		//process the image tag
		getImageList ($folder_name,$input_file);
	}
	
	/*
		For each image, change the path and get its size.
		For each section, change the path.
		@param string $folder_name the path to the book directory
		@param string $input_file the path to the input XHTML file
	 */
	function getImageList ($folder_name,$input_file) {
		$dir_name = "repository";
				
		$str = file_get_contents($input_file);
		
		//protect html entities
		$str = str_replace("@&#@", "&#", $str);
		$str = str_replace("&#", "@&#@", $str);
		
		preg_match_all('/<img[^>]* src="([^"]+)"[^>]+>/i', $str, $matches, PREG_SET_ORDER);
		
		foreach ($matches as $val) {
			$img_name = basename($val[1]);
			$new_img_name = $dir_name."/".$img_name;
			$width = 20;
			$height = 20;
			if (file_exists($folder_name."/".$new_img_name) == true) {
				list($width, $height, $type, $attr) = getimagesize($folder_name."/".$new_img_name);//get width and height
			}
			$new_img_tag = "<img src=\"".$new_img_name."\" width=\"".$width."\" height=\"".$height."\" />";
			$str = str_replace($val[0], $new_img_tag, $str);
		}
		
		$tag_list = array("section", "newpage", "h[\d]+");
		for ($j = 0; $j < count($tag_list); $j++) {
			$tag = $tag_list[$j];
			preg_match_all('/<'.$tag.'[^>]* filename="([^"]+)"[^>]+>/i', $str, $matches, PREG_SET_ORDER);
			foreach ($matches as $val) {
				$img_list = explode(";", $val[1]);
				$new_img_list = "";
				for ($i = 0; $i < count($img_list); $i++) {
					if ($i > 0) {
						$new_img_list = $new_img_list.";";
					}
					$new_img_list = $new_img_list.basename($img_list[$i]);
				}
				$new_tag = str_replace($val[1], $new_img_list, $val[0]);
				$str = str_replace($val[0], $new_tag, $str);
			}
		}
		
		//save the file
		$file = modifyFile($input_file,"w");
		if (!$file) die ("cannot open the file");
		fwrite($file, $str);
		fclose($file);
	}
	
	/*
		Append the text file into the current template file
		@param string $folder_name the directory path to the template file
		@param string $input_file the filename for the text file
	*/
	function appendTemplateText ($folder_name, $input_file) {
		$data = file_get_contents($folder_name."/".$GLOBALS["book"]);
		$new_data = file_get_contents($input_file);
		
		//remove the duplicate html, head, body tags
		preg_match_all('/<html[^>]*>/i', $new_data, $meta_matches, PREG_SET_ORDER);
		foreach ($meta_matches as $meta_val) {
			$new_data = str_replace($meta_val[0],"",$new_data);
		}
		$dupl_tags = array("head","body","html");
		for ($k = 0; $k < count($dupl_tags); $k++) {
			$new_data = str_replace("<".$dupl_tags[$k].">","",$new_data);
			$new_data = str_replace("</".$dupl_tags[$k].">","",$new_data);
		}
		
		//remove duplicate metadata in new text file as we assume
		//that the one defines in template file is the right one
		//add the remaining metadata in the new text file to the template
		$add_meta = "";
		$anchor_meta = "";
		preg_match_all('/<metadata[^>]+name="([^"]+)"[^>]*>[^<]*<\/metadata>/i', $new_data, $meta_matches, PREG_SET_ORDER);
		foreach ($meta_matches as $meta_val) {
			if (strcmp(strtolower($meta_val[1]),"title") != 0) {
				$btag = $meta_val[1];
				preg_match_all('/<metadata[^>]+name="'.$btag.'"[^>]*>[^<]*<\/metadata>/i', $data, $matches, PREG_SET_ORDER);
				if (count($matches) == 0) {
					$add_meta = $add_meta.$meta_val[0]."\n";
				} else {
					foreach ($matches as $val) {
						$anchor_meta = $val[0];
					}
				}
				$new_data = str_replace($meta_val[0],"",$new_data);
			}
		}
		preg_match_all('/<title>[^<]*<\/title>/i', $new_data, $meta_matches, PREG_SET_ORDER);
		foreach ($meta_matches as $meta_val) {
			preg_match_all('/<title>[^<]*<\/title>/i', $data, $matches, PREG_SET_ORDER);
			if (count($matches) == 0) {
				$add_meta = $meta_val[0]."\n".$add_meta;
			}
			$new_data = str_replace($meta_val[0],"",$new_data);
		}
		if (strlen($anchor_meta) == 0) {
			preg_match_all('/<metadata[^>]+name="([^"]+)"[^>]*>[^<]*<\/metadata>/i', $data, $matches, PREG_SET_ORDER);
			foreach ($matches as $val) {
				$btag = $val[1];
				if (strcmp(strtolower($val[1]),"title") != 0) {
					$anchor_meta = $val[0];
				}
			}
		}
		if (strlen($anchor_meta) == 0) {
			preg_match_all('/<html>[\s\r\n]*((<description>)?)/i', $data, $matches, PREG_SET_ORDER);
			foreach ($matches as $val) {
				if (strcmp(strtolower($val[1], "<description>")) != 0) {
					$add_meta = "<description>".$add_meta."</description>";
				}
				$anchor_meta = $val[0];
			}
		}
		$data = str_replace($anchor_meta, $anchor_meta."\n".$add_meta, $data);
		
		//remove the empty description tag
		preg_match_all('/<description>[\s\r\n]*<\/description>/i', $new_data, $desc_matches, PREG_SET_ORDER);
		foreach ($desc_matches as $desc_val) {
			$new_data = str_replace($desc_val[0], "", $new_data);
		}
		
		//remove exisiting bob from the file first
		$bob_pos = stripos($data,"<bob>");
		if ($bob_pos !== false) {
			$ebob_pos = stripos($data,"</bob>");
			$data = substr($data, 0, $bob_pos).substr($data,$ebob_pos + 6);
		} 
		
		//append to the end of template
		//let's assume that at the end of template file there will always be </html>
		//and there's only one
		preg_match_all('/((<\/section>[\s\r\n]*)+(<\/body>)?[\s\r\n]*)<\/html>/i', $data, $tag_matches, PREG_SET_ORDER);
		foreach ($tag_matches as $tag_val) {
			$data = str_replace($tag_val[0], $new_data.$tag_val[0], $data);
		}
		if (count($tag_matches) == 0) {
			preg_match_all('/((<newpage \/>[\s\r\n]*){3}(<\/body>)?[\s\r\n]*)<\/html>/i', $data, $tag_matches, PREG_SET_ORDER);
			if (count($tag_matches) == 0) {
				$data = str_replace("</html>", $new_data."</html>", $data);
			} else {
				foreach ($tag_matches as $tag_val) {
					$data = str_replace($tag_val[0], "<newpage />\n".$new_data."\n</html>", $data);
				}
			}
		}
		
		//save the template file
		$html_file = $GLOBALS["book"];
		$file = modifyFile($folder_name."/".$html_file,"w");
		if (!$file) die ("cannot open the file");
		fwrite($file, $data);
		fclose($file);
	}
?>